package api

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"virtual-resource-schedule-service/middleware"
	"virtual-resource-schedule-service/model/common"
	"virtual-resource-schedule-service/utils/auth"
)

func GenToken(ctx *gin.Context) {
	authId := ctx.Request.Header.Get(auth.RequestAuthIdName)
	requestId := ctx.Request.Header.Get(auth.RequestIdName)

	if authId == "" || requestId == "" {
		response := middleware.APIResponse{
			Code:    "10000403",
			Message: "无权限访问当前API",
			Success: false,
		}
		middleware.ResponseJSON(ctx, http.StatusUnauthorized, response)
		// 不允许访问
		ctx.Abort()
		return
	}
	if authId != auth.StaticAuthID {
		response := middleware.APIResponse{
			Code:    "10000403",
			Message: "无效AuthID",
			Success: false,
		}
		middleware.ResponseJSON(ctx, http.StatusUnauthorized, response)
		// 不允许访问
		ctx.Abort()
		return
	}

	claims := common.RequestClaims{
		RequestID: requestId,
		AuthID:    authId,
	}
	jwt := auth.NewJWT()
	token, err := jwt.GenerateToken(claims)
	if err != nil {
		zap.S().Error(err)
	}
	response := middleware.APIResponse{
		Code:    "00000000",
		Message: "Token生成成功",
		Data: map[string]interface{}{
			"token":  token,
			"expire": 1800,
		},
		Success: true,
	}
	middleware.ResponseJSON(ctx, http.StatusOK, response)
}

func RefreshToken(ctx *gin.Context) {
	token := ctx.Request.Header.Get(auth.JwtTokenName)
	authId := ctx.Request.Header.Get(auth.RequestAuthIdName)
	requestId := ctx.Request.Header.Get(auth.RequestIdName)

	if token == "" || authId == "" || requestId == "" {
		response := middleware.APIResponse{
			Code:    "10000403",
			Message: "无权限访问当前API",
			Success: false,
		}
		middleware.ResponseJSON(ctx, http.StatusUnauthorized, response)
		// 不允许访问
		ctx.Abort()
		return
	}
	if authId != auth.StaticAuthID {
		response := middleware.APIResponse{
			Code:    "10000403",
			Message: "无效AuthID",
			Success: false,
		}
		middleware.ResponseJSON(ctx, http.StatusUnauthorized, response)
		// 不允许访问
		ctx.Abort()
		return
	}

	claims := common.RequestClaims{
		RequestID: requestId,
		AuthID:    authId,
	}
	jwt := auth.NewJWT()
	token, err := jwt.RefreshToken(claims, token)
	if err != nil {
		zap.S().Error(err)
	}
	response := middleware.APIResponse{
		Code:    "00000000",
		Message: "Token刷新成功",
		Data: map[string]interface{}{
			"token":  token,
			"expire": 1800,
		},
		Success: true,
	}
	middleware.ResponseJSON(ctx, http.StatusOK, response)
}
